package com.cuit.controller;



import com.cuit.common.Constants;
import com.cuit.common.PageResult;
import com.cuit.common.Result;
import com.cuit.entity.User;
import com.cuit.service.UserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public Result getUsers(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String keyword) {

        PageInfo<User> pageInfo = userService.getUsers(page, size, keyword);
        PageResult result = new PageResult(pageInfo.getList(), pageInfo.getTotal());
        System.out.println(result);
        return Result.success(result);
    }

    @PostMapping
    public Result addUser(@RequestBody User user) {
        userService.addUser(user);
        return Result.success();
    }

    @PutMapping("/{id}")
    public Result updateUser(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        userService.updateUser(user);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result deleteUser(@PathVariable Long id) {
        try {
            userService.deleteUser(id);
            return Result.success();
        } catch (Exception e) {
            return Result.error(Constants.CODE_500, "删除用户失败"); // 使用 error 方法
        }
    }


    // 新增密码修改接口（明文存储）
    @PutMapping("/{id}/password")
    public Result updatePassword(
            @PathVariable Long id,
            @RequestBody Map<String, String> request) {
        String newPassword = request.get("newPassword"); // 直接获取新密码
        userService.updatePassword(id, newPassword); // 无需旧密码验证
        return Result.success();
    }

    // 更新用户信息接口
    @PutMapping("/{id}/info")
    public Result updateUserInfo(
            @PathVariable Long id,
            @RequestBody User user
    ) {
        try {

            // 2. 更新用户信息
            user.setId(id);
            userService.updateUserInfo(user);

            // 3. 返回更新后的用户信息
            User updatedUser = userService.getUserById(id);
            return Result.success(updatedUser);
        } catch (Exception e) {
            return Result.error(Constants.CODE_500, "服务器内部错误: " + e.getMessage());
        }
    }


}